package com.zjh.controller;

import com.zjh.pojo.User;
import com.zjh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    @Qualifier("UserServiceImpl")
    private UserService userService;

    @RequestMapping("/allUser")
    public String queryAllUser(Model model) {
        List<User> list = userService.queryAllUsers();
        model.addAttribute("list", list);
        return "allUser";
    }

    @RequestMapping("/login")
    public String login(String name, String password, HttpSession session) {
        Map<String, String> map = new HashMap<>();
        map.put("name", name);
        map.put("password", password);
        User user = userService.login(map);
        System.out.println("login++++++++++++++++++++qweqwe" + user);
        if (user != null) {
            session.setAttribute("user", user.getName());
            return "redirect:/book/allBook";
        }
        return "redirect:/user/toLogin";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "redirect:/";
    }

    @RequestMapping("/toAddUser")
    public String toAddUser() {
        return "addUser";
    }

    @RequestMapping("/addUser")
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:/user/allUser";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(int id, Model model) {
        User user = userService.queryById(id);
        model.addAttribute("QueryUser", user);
        return "upDateUser";
    }

    @RequestMapping("/updateUser")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:/user/allUser";
    }

    @RequestMapping("/deleteUserById/{userId}")
    public String deleteUserById(@PathVariable("userId") int id) {
        userService.deleteUserById(id);
        return "redirect:/user/allUser";
    }

    @RequestMapping("/queryUserByName")
    public String queryUserByName(String queryUserName, Model model) {
        List<User> list = userService.queryUserByName(queryUserName);
        model.addAttribute("list", list);
        return "allUser";
    }
}
